package r

import (
    "device-modbus/pkg/base"
    "device-modbus/pkg/e"
    "errors"
    "github.com/cloudwego/hertz/pkg/app"
    "net/http"
)

var Default = &response{}

func OKData(c *app.RequestContext, data interface{}) {
    newResponse := Default.Clone()
    newResponse.Response.Code = e.SUCCESS
    newResponse.Response.Msg = e.GetMsg(e.SUCCESS)
    newResponse.Data = data
    c.AbortWithStatusJSON(http.StatusOK, newResponse)
}
func OkOrError(c *app.RequestContext, err error) {
    if err != nil {
        ErrorMsg(c, err.Error())
        return
    }
    OK(c)
    return
}
func OkOrErrorData(c *app.RequestContext, data interface{}, err error) {
    if err != nil {
        ErrorMsg(c, err.Error())
        return
    }
    OKData(c, data)
    return
}
func OKDataMsg(c *app.RequestContext, data interface{}, msg string) {
    newResponse := Default.Clone()
    newResponse.Response.Code = e.SUCCESS
    if msg == "" {
        msg = e.GetMsg(e.SUCCESS)
    }
    newResponse.Response.Msg = msg
    newResponse.Data = data
    c.AbortWithStatusJSON(http.StatusOK, newResponse)
}
func OK(c *app.RequestContext) {
    newResponse := Default.Clone()
    newResponse.Response.Code = e.SUCCESS
    newResponse.Response.Msg = e.GetMsg(e.SUCCESS)
    c.AbortWithStatusJSON(http.StatusOK, newResponse)
}
func R(c *app.RequestContext, data interface{}, err error) {
    if err != nil {
        ErrorMsg(c, err.Error())
    } else {
        OKData(c, data)
    }
}

// Error 失败数据处理
func ErrorMsg(c *app.RequestContext, msg string) {
    res := Default.Clone()
    res.Response.Msg = msg
    res.Response.Code = e.ERROR
    c.Error(errors.New(res.Response.Msg))
    c.AbortWithStatusJSON(http.StatusOK, res)
}
func ErrorV(c *app.RequestContext, msg string) {
    res := Default.Clone()
    res.Response.Msg = msg
    res.Response.Code = e.INVALID_PARAMS
    c.Error(errors.New(res.Response.Msg))
    c.AbortWithStatusJSON(http.StatusOK, res)
}

// Error 失败数据处理
func Error(c *app.RequestContext, code int) {
    res := Default.Clone()
    res.Response.Msg = e.GetMsg(code)
    res.Response.Code = code
    c.Error(errors.New(res.Response.Msg))
    c.AbortWithStatusJSON(http.StatusOK, res)
}

// Error 失败数据处理
func Error500(c *app.RequestContext) {
    res := Default.Clone()
    res.Response.Msg = e.GetMsg(e.ERROR)
    res.Response.Code = e.ERROR
    c.Error(errors.New(res.Response.Msg))
    c.AbortWithStatusJSON(http.StatusOK, res)
}

func PageOk(c *app.RequestContext, result interface{}, count int64, page2 base.Page) {
    var page page
    page.PageIndex = page2.PageIndex
    page.PageSize = page2.PageSize
    page.List = result
    page.Count = count
    OKData(c, page)
}
